package com.dyh.quickdemozwei;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Slf4j
public class TestListRead {

    ThreadPoolExecutor poolExecutor;
    {
        this.poolExecutor = new ThreadPoolExecutor(3,6,
                300, TimeUnit.SECONDS,
//                new SynchronousQueue<>(),
                new LinkedBlockingQueue<>(200),
                new ThreadFactoryBuilder().setNameFormat("pool-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    Consumer<Integer> consumer = e->{
        log.info("{} 开始消费-{}",Thread.currentThread().getName(),e);
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        log.info("{} 结束消费-{}",Thread.currentThread().getName(),e);
    };

    @Test
    public void test(){
        List<Integer> datas = Lists.newArrayList(1,2,3,4,5);


        byte[] tags = new byte[datas.size()];


        for (int i = 0;i<datas.size();i++){
            int d = datas.get(i);

            int finalI = i;
            poolExecutor.submit(()->{
                consumer.accept(d);
                tags[finalI]=1;
            });

        }

        Runnable timeWait = ()->{

            l1:
            for (;;){
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                for (int i=tags.length-1;i>=0;i--){
                    if (tags[i]==0)
                        continue l1;
                }

                break;
            }

        };


        Thread waitThread = new Thread(timeWait::run);
        waitThread.setName("waitThread");
        waitThread.start();

        try {
            waitThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("结束");
    }

}
